package com.newgoldcurrency.activities.emailverifyandmodify;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.databinding.ActivityEmailVerificationBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;
import com.newgoldcurrency.view.LoadingDialog;
import com.newgoldcurrency.view.VerificationCodeView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class EmailVerificationActivity extends AppCompatActivity {
    private ActivityEmailVerificationBinding binding;
    int time=60;
    Handler handler=new Handler();
    private final List<Call> calls =new ArrayList<>();
    Runnable runnable=new Runnable() {
        @SuppressLint("SetTextI18n")
        @Override
        public void run() {
            if (time>0){
                time--;
                handler.postDelayed(this,1000);
                if (binding!=null)binding.emailVerificationSend.setText(time+"s");
            }else {
                time=60;
                if (binding!=null)binding.emailVerificationSend.setEnabled(true);
                if (binding!=null)binding.emailVerificationSend.setText("Send");
            }
        }
    };
    private long mClickTime;
    private LoadingDialog loading_dialog;

    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
    private String verifyCode="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityEmailVerificationBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        loading_dialog=new LoadingDialog(this);
        binding.emailVerifyBack.setOnClickListener(v -> finish());
        binding.emailVerifyEmail.setText(App.userBean.mail);
        binding.emailVerificationSend.setOnClickListener(v -> {
            if (checkDoubleClick()) {
                if (loading_dialog != null && !loading_dialog.isShowing()) {
                    loading_dialog.show();

                    if (binding.emailVerifyEmail.getText().toString().equals("")){
                        Tools.toast(getString(R.string.please_input_email));
                        loading_dialog.dismiss();
                    }else {
                        HashMap<String, String> map=new HashMap<>();
                        map.put("mail",binding.emailVerifyEmail.getText().toString());
                        map.put("type","verify");
                        Network.post(map, "user/getVerificationCode", call -> {
                            call.enqueue(new Callback() {
                                @Override
                                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                    runOnUiThread(() -> {
                                        e.printStackTrace();
                                        loading_dialog.dismiss();
                                    });
                                }
                                @Override
                                public void onResponse(@NonNull Call call, @NonNull Response response) {
                                    runOnUiThread(() -> {
                                        loading_dialog.dismiss();
                                        try {
                                            String str = Objects.requireNonNull(response.body()).string();
                                            if (Tools.isJson(str)) {
                                                JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
                                                if (jo.get("message").getAsString().equals("Sent successfully")) {
                                                    startDelay();
                                                }
                                                Tools.toast(jo.get("message").getAsString());
                                            }
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }

                                    });
                                }
                            });
                            calls.add(call);
                        });
                    }
                }
            }
        });
        binding.forgetPasswordVerify.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
            @Override
            public void onTextChange(View view, String content) {
                if (content.length()==4){
                    binding.emailVerificationVerify.setEnabled(true);
                    binding.emailVerificationVerify.setBackgroundResource(R.drawable.bg_button);
                }else {
                    binding.emailVerificationVerify.setEnabled(false);
                    binding.emailVerificationVerify.setBackgroundResource(R.drawable.bg_button_disable);
                }
            }
            @Override
            public void onComplete(View view, String content) {
                verifyCode=content;
            }
        });
        binding.emailVerificationVerify.setOnClickListener(v -> {
            if (checkDoubleClick()){
                HashMap<String, String> map=new HashMap<>();
                map.put("mail",binding.emailVerifyEmail.getText().toString());
                map.put("code",verifyCode);
                map.put("token",App.sp.getString("token",""));
                Network.post(map, "user/verifyMail", call -> {
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            e.printStackTrace();
                        }
                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) {
                            runOnUiThread(() -> {
                                try {
                                    String str= Objects.requireNonNull(response.body()).string();
                                    if (Tools.isJson(str)){
                                        JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
                                        if(jo.get("message").getAsString().equals("Verify mailbox success")){
                                            SharedPreferences.Editor edit = App.sp.edit();
                                            edit.putString("token",jo.get("data").getAsJsonObject().get("token").getAsString());
                                            edit.apply();
                                            setResult(2);
                                            startActivity(new Intent(EmailVerificationActivity.this,EmailVerifyFinishActivity.class));
                                            finish();
                                        }
                                        Tools.toast(jo.get("message").getAsString());
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            });
                        }
                    });
                    calls.add(call);
                });
            }
        });
    }
    private void startDelay() {
        handler.postDelayed(runnable,0);
        binding.emailVerificationSend.setEnabled(false);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Call call :calls) {
            call.cancel();
        }
        handler.removeCallbacks(runnable);
        binding=null;
    }
}